<template>
  <div class="box-yuyi">
    <div class="box-left">
      <container-nav :treeData="categoryTreeData"
                     :loading="treeLoading"
                     :setLabelId="leftCategoryProp"
                     @handleNodeClick="handleNodeClick"></container-nav>
    </div>
    <div class="box-content">
      <div class="fun-box" v-if="idCategory">
        <el-button type="primary" size="small" @click="handleAdd">新增</el-button>

        <div class="head-search">
          <search @onSubmit="onSearch">
            <el-form-item>
              <el-input placeholder="请输入内容" clearable v-model="searchData.val" size="small" class="input-with-select">
                <el-select v-model="searchData.select" clearable slot="prepend" placeholder="请选择">
                  <el-option v-for="(item, index) in searchOptions"
                             :key="index"
                             :label="item.mdName"
                             :value="item.mdCode"></el-option>
                </el-select>
              </el-input>
            </el-form-item>
          </search>
        </div>
      </div>
      <div class="list-box" v-if="idCategory">

        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="tableData"
                   :page.sync="page"
                   ref="crud"
                   @current-change="handleCurrentChange"
                   @size-change="handleSizeChange"
                   @row-del="rowDel"
        >

          <template slot="menu" slot-scope="{row}">
            <el-button size="small" v-if="[2, 4, 6].includes(Number(row.status))"
                       @click="handleDownload(row)"
                       class="download"
                       target="_blank">
              <i class="el-icon-download"></i>
              下载日志
            </el-button>
          </template>

          <template slot="status" slot-scope="{row}">
            <span :style="{color: statusList[row.status].color}">{{ statusList[row.status].label }}</span>
          </template>

        </avue-crud>

      </div>
    </div>

    <el-dialog :title="dialogTitle"
               :width="dialogWidth"
               top="5vh"
               :destroy-on-close="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="dialogShow">
      <el-form :model="ruleForm"
               ref="ruleForm"
               :rules="rules"
               label-width="130px"
               class="demo-ruleForm">
        <el-form-item label="创建导入项目：" prop="describe">
          <el-input type="textarea"
                    :autosize="autosize"
                    show-word-limit
                    maxlength="500"
                    placeholder="请输入需创建的项目名称  如：2021年文书简化档案"
                    v-model="ruleForm.describe"></el-input>
        </el-form-item>
        <el-form-item label="导入项目备注：">
          <el-input type="textarea"
                    :autosize="autosize"
                    show-word-limit
                    maxlength="1000"
                    placeholder="请填写备注  如：2021年第十次导入"
                    v-model="ruleForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="导入用户：" style="margin-bottom: 0">
          <span>{{ruleForm.userName}}</span>
        </el-form-item>
        <el-form-item label="创建时间：">
          <span>{{ruleForm.importCurrentTime}}</span>
        </el-form-item>

        <el-form-item style="text-align: right">
          <el-button size="small" :loading="subLoading" @click="dialogShow = false">取消</el-button>
          <el-button type="primary" :loading="subLoading" size="small" @click="handleImport">创建导入</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-drawer
      :title="'选择数据源'"
      :size="'80%'"
      :direction="'rtl'"
      :visible.sync="drawer"
      :destroy-on-close="true"
    >
      <change-data-source-receive :idCategoryList="idCategoryList"
                                  :id="rowId"
                                  @handleSuccess="handleSuccess"></change-data-source-receive>

    </el-drawer>

  </div>
</template>

<script>
import Search from '../../../components/search/search'
import ContainerNav from '../../../components/containerNav/containerNav'
import { mapActions } from 'vuex'
import { getCategoryTree, getEntityCategory } from '../../../api/category/category'
import { mapFields } from 'vuex-map-fields'
import { addImportList, delImportList, downloadErrJournal, getImportList } from '../../../api/dataManage/dataImport'
import ChangeDataSourceReceive from './components/changeDataSourceReceive'
import { getToday } from '../../../util/util'

export default {
  name: 'DataImportIndex',
  components: {
    ChangeDataSourceReceive,
    Search,
    ContainerNav
  },
  data () {
    return {
      statusList: {
        0: {
          label: '未开始',
          color: '#909399'
        },
        1: {
          label: '文件包解压中',
          color: '#666'
        },
        2: {
          label: '解压失败',
          color: '#F56C6C'
        },
        3: {
          label: '四性检测中',
          color: '#666'
        },
        4: {
          label: '检测未通过',
          color: '#67C23A'
        },
        5: {
          label: '正在导入中',
          color: '#666'
        },
        6: {
          label: '导入失败',
          color: '#F56C6C'
        },
        7: {
          label: '导入成功',
          color: '#67C23A'
        }
      },
      fileList: [],
      treeLoading: true,
      categoryTreeData: [],
      leftCategoryProp: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      searchData: {
        // 搜索條件
        select: 'describe',
        val: ''
      },
      searchOptions: [{
        mdName: '接收项目名称',
        mdCode: 'describe'
      }, {
        mdName: '接收时间',
        mdCode: 'gmtCreate'
      }, {
        mdName: '接收用户',
        mdCode: 'userCreate'
      }], // 搜索数据
      idCategory: '',
      idTable: '',
      rowId: '',
      idCategoryList: [], // 根据门类id获取实体门类表
      params: [], // 搜索条件
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        pageSizes: [20, 40, 60, 80],
        total: 0
      },
      tableData: [],
      dialogShow: false, // 是否弹出弹窗
      dialogTitle: '', // 弹窗title
      dialogWidth: '', // 弹窗宽度
      autosize: {
        minRows: 4,
        maxRows: 6
      },
      ruleForm: {
        // 新增表单
        describe: '', // 创建导入项目
        idCategory: '',
        userName: '', // 用户名
        importCurrentTime: ''
      },
      rules: {
        describe: [
          {
            required: true,
            message: '请输入创建导入项目',
            trigger: 'blur'
          }
        ]
      },
      subLoading: false,
      drawer: false
    }
  },
  mounted () {
    // 默认收起左侧导航栏
    this.getLeftCategory()
    this.setNavNarrow(true)
  },
  computed: {
    ...mapFields('profile/profile', {
      userInfo: 'retrieved'
    }),
    importTime () {
      return getToday()
    },
    option () {
      return {
        align: 'center',
        menuAlign: 'center',
        header: false,
        border: true,
        size: 'medium',
        height: 'calc(100vh - 210px)',
        index: true, // 显示序号
        indexLabel: '序号', // 显示序号
        selection: false, // 多选
        editBtn: false, // 行内编辑按钮
        delBtn: true, // 行内删除按钮
        viewBtn: false, // 行内查看按钮
        menuWidth: 180,
        column: [
          {
            label: '接收项目名称',
            prop: 'describe',
            minWidth: 200,
            align: 'left'
          },
          {
            label: '接收时间',
            prop: 'gmtCreate',
            type: 'date',
            width: 180,
            format: 'yyyy-MM-dd hh:mm:ss',
            valueFormat: 'yyyy-MM-dd hh:mm:ss'
          },
          {
            label: '接收用户',
            prop: 'userCreate'
          },
          {
            label: '接收备注说明',
            prop: 'remark',
            width: 200
          },
          {
            label: '接收状态',
            prop: 'status',
            width: 150,
            solt: true
          }
        ]
      }
    }
  },
  methods: {
    ...mapActions('profile/navNarrow', ['setNavNarrow']),
    getLeftCategory () {
      // 左侧获取门类
      getCategoryTree('qtModel', this.$route.query.isNotAjJnNode).then(res => {
        this.categoryTreeData = res.data.data
        this.treeLoading = false
      }).catch(() => {
        this.treeLoading = false
      })
    },
    onSearch () {
      // 搜索
      this.params = []
      if (this.searchData.val) {
        this.params = [{
          op: 'like',
          name: this.searchData.select,
          value: this.searchData.val
        }]
      }
      this.onLoad()
    },
    onLoad () {
      // 加载列表
      this.loading = true
      const query = {
        pageSize: this.page.pageSize,
        pageNo: this.page.currentPage,
        params: [{
          name: 'idCategory',
          op: 'eq',
          value: this.idCategory
        }]
      }
      if (this.params.length > 0) {
        query.params = query.params.concat(this.params)
      }
      getImportList(query).then(res => {
        this.tableData = res.data.data.list
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
    handleCurrentChange (currentPage) {
      // 翻页 第几页
      this.page.currentPage = currentPage
    },
    handleSizeChange (pageSize) {
      // 翻页 一页多少条
      this.page.pageSize = pageSize
    },
    handleNodeClick (data) {
      if (data.idCategory) {
        this.idCategory = data.idCategory
        this.ruleForm.idCategory = data.idCategory
        this.ruleForm.userName = this.userInfo.userName
        this.idTable = data.table[0].idTable
        this.onLoad()
        getEntityCategory(this.idCategory).then(res => {
          this.idCategoryList = res.data.data
        })
      }
    },
    handleAdd () {
      // 新增弹窗
      this.dialogShow = true
      this.dialogTitle = '新增'
      this.dialogWidth = '550px'
      this.ruleForm.importCurrentTime = this.importTime
    },
    handleImport () {
      // 创建导入
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.subLoading = true
          addImportList(this.ruleForm).then(res => {
            this.rowId = res.data.data
            this.onLoad()
            this.drawer = true
            this.dialogShow = false
            this.subLoading = false
          }).catch(() => {
            this.subLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleSuccess () {
      // 确认接收
      this.drawer = false
      this.ruleForm.describe = '' // 创建导入项目
      this.ruleForm.userName = '' //  用户名
      this.ruleForm.importCurrentTime = '' //
    },
    handleDownload (row) {
      // 下载
      downloadErrJournal(row.id).then(res => {
        this.download(res.data, row.describe + '.' + res.headers['content-type'].split('/')[0])
      })
    },
    download (data, fileName) {
      const blob = new Blob([data])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.target = '_blank'
      downloadElement.download = fileName // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    },
    rowDel (row, index) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delImportList([row.id]).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.onLoad()
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '../../../styles/mixin';

  .box-yuyi {

    .fun-box {
      @include fj;
      align-items: center;
      padding: 15px 0;

      .upload-demo {
        margin-right: 10px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }

      .head-search {
        ::v-deep .el-form-item {
          margin-bottom: 0;

          .el-form-item__content {
            line-height: normal;
          }

          &.search-btn {
            margin: 0;
          }
        }
      }
    }

    .fail {
      margin-top: 10px;

      hgroup {
        line-height: 30px;
        color: #333;
      }

      ul {
        max-height: calc(90vh - 170px);
        overflow-y: auto;

        li {
          line-height: 28px;
          font-size: 13px;
          margin-left: 15px;
        }
      }
    }

    .download {
      color: #409EFF;
      margin-left: 10px;
    }

    .demo-ruleForm {
      padding-right: 40px;
    }
  }
</style>
